"""
预订管理路由
"""
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from utils import ApiResponse
from services.reservation_service import ReservationService

api_bp = Blueprint('reservation', __name__, url_prefix='/admin')
reservation_service = ReservationService()


@api_bp.route('/reservations', methods=['GET'])
@jwt_required()
def get_reservations():
    """获取预订列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        room_number = request.args.get('room_number', '').strip()
        status = request.args.get('status', type=int)
        check_in_start = request.args.get('check_in_start')
        check_in_end = request.args.get('check_in_end')
        
        data = reservation_service.get_reservations_paginated_dto(
            page=page,
            per_page=per_page,
            room_number=room_number,
            status=status,
            check_in_start=check_in_start,
            check_in_end=check_in_end
        )
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/reservations/<int:reservation_id>', methods=['GET'])
@jwt_required()
def get_reservation(reservation_id):
    """获取预订详情"""
    try:
        data = reservation_service.get_reservation_dto(reservation_id)
        if not data:
            return ApiResponse.error(msg='预订不存在', code=404)
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/reservations', methods=['POST'])
@jwt_required()
def create_reservation():
    """创建预订"""
    try:
        data = request.get_json()
        
        required_fields = ['guestId', 'roomId', 'checkIn', 'checkOut', 'totalPrice']
        for field in required_fields:
            if field not in data or not data[field]:
                return ApiResponse.error(msg=f'缺少必填字段: {field}', code=400)
        
        from datetime import datetime
        check_in = data['checkIn']
        check_out = data['checkOut']
        
        # 解析日期时间，支持多种格式
        if isinstance(check_in, str):
            try:
                # 尝试解析完整日期时间格式
                check_in = datetime.strptime(check_in, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                # 尝试解析日期格式
                try:
                    check_in = datetime.strptime(check_in, '%Y-%m-%d')
                    # 默认设置为14:00:00
                    check_in = check_in.replace(hour=14, minute=0, second=0)
                except ValueError:
                    return ApiResponse.error(msg='checkIn日期格式错误，请使用YYYY-MM-DD或YYYY-MM-DD HH:MM:SS', code=400)
        
        if isinstance(check_out, str):
            try:
                # 尝试解析完整日期时间格式
                check_out = datetime.strptime(check_out, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                # 尝试解析日期格式
                try:
                    check_out = datetime.strptime(check_out, '%Y-%m-%d')
                    # 默认设置为12:00:00
                    check_out = check_out.replace(hour=12, minute=0, second=0)
                except ValueError:
                    return ApiResponse.error(msg='checkOut日期格式错误，请使用YYYY-MM-DD或YYYY-MM-DD HH:MM:SS', code=400)
        
        # 验证日期逻辑
        if check_in >= check_out:
            return ApiResponse.error(msg='退房日期必须晚于入住日期', code=400)
        
        result = reservation_service.create_reservation_dto(
            guest_id=data['guestId'],
            room_id=data['roomId'],
            check_in=check_in,
            check_out=check_out,
            total_price=data['totalPrice'],
            deposit=data.get('deposit', 0)
        )
        
        return ApiResponse.success(data=result, msg='预订创建成功', code=201)
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/reservations/<int:reservation_id>', methods=['PUT'])
@jwt_required()
def update_reservation(reservation_id):
    """更新预订"""
    try:
        data = request.get_json() or {}
        
        update_data = {}
        field_mapping = {
            'guestId': 'guest_id',
            'roomId': 'room_id',
            'totalPrice': 'total_price',
            'deposit': 'deposit',
            'status': 'status'
        }
        
        for api_field, model_field in field_mapping.items():
            if api_field in data and data[api_field] is not None:
                update_data[model_field] = data[api_field]
        
        # 处理日期字段
        if 'checkIn' in data and data['checkIn'] is not None:
            from datetime import datetime
            check_in = data['checkIn']
            if isinstance(check_in, str):
                try:
                    check_in = datetime.strptime(check_in, '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    check_in = datetime.strptime(check_in, '%Y-%m-%d')
                    check_in = check_in.replace(hour=14, minute=0, second=0)
            update_data['check_in'] = check_in
        
        if 'checkOut' in data and data['checkOut'] is not None:
            from datetime import datetime
            check_out = data['checkOut']
            if isinstance(check_out, str):
                try:
                    check_out = datetime.strptime(check_out, '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    check_out = datetime.strptime(check_out, '%Y-%m-%d')
                    check_out = check_out.replace(hour=12, minute=0, second=0)
            update_data['check_out'] = check_out
        
        # 验证日期逻辑
        if 'check_in' in update_data and 'check_out' in update_data:
            if update_data['check_in'] >= update_data['check_out']:
                return ApiResponse.error(msg='退房日期必须晚于入住日期', code=400)
        elif 'check_in' in update_data:
            # 获取当前的check_out进行验证
            reservation = reservation_service.get_by_id(reservation_id)
            if reservation and update_data['check_in'] >= reservation.check_out:
                return ApiResponse.error(msg='退房日期必须晚于入住日期', code=400)
        elif 'check_out' in update_data:
            # 获取当前的check_in进行验证
            reservation = reservation_service.get_by_id(reservation_id)
            if reservation and reservation.check_in >= update_data['check_out']:
                return ApiResponse.error(msg='退房日期必须晚于入住日期', code=400)
        
        result = reservation_service.update_reservation_dto(reservation_id, **update_data)
        if not result:
            return ApiResponse.error(msg='预订不存在', code=404)
        
        return ApiResponse.success(data=result, msg='预订更新成功')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/reservations/<int:reservation_id>', methods=['DELETE'])
@jwt_required()
def delete_reservation(reservation_id):
    """删除预订"""
    try:
        result = reservation_service.delete(reservation_id)
        if not result:
            return ApiResponse.error(msg='预订不存在', code=404)
        
        return ApiResponse.success(msg='预订删除成功')
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/reservations/<int:reservation_id>/confirm', methods=['POST'])
@jwt_required()
def confirm_reservation(reservation_id):
    """确认预订"""
    try:
        reservation = reservation_service.confirm_reservation(reservation_id)
        if not reservation:
            return ApiResponse.error(msg='预订不存在', code=404)
        
        return ApiResponse.success(data=reservation_service.mapper.to_dict(reservation), msg='预订已确认')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/reservations/<int:reservation_id>/cancel', methods=['POST'])
@jwt_required()
def cancel_reservation(reservation_id):
    """取消预订"""
    try:
        reservation = reservation_service.cancel_reservation(reservation_id)
        if not reservation:
            return ApiResponse.error(msg='预订不存在', code=404)
        
        return ApiResponse.success(data=reservation_service.mapper.to_dict(reservation), msg='预订已取消')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)

